<template>
    <div class="createPost-container">
      <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
  
        <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
          <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
            发布
          </el-button>
          <!-- <el-button v-loading="loading" type="warning" @click="draftForm">
            草稿
          </el-button> -->
        </sticky>
  
        <div class="createPost-main-container">
          <el-row>
            <el-col :span="24">
              <el-form-item style="margin-bottom: 40px;" prop="title">
                <MDinput v-model="postForm.name" :maxlength="100" name="name" required>
                  标题
                </MDinput>
              </el-form-item>
  
              <div class="postInfo-container">
                <el-row>
                  <!-- 发布人 -->
                  <el-col :span="12">
                    <el-form-item label-width="90px" label="发布人:" class="postInfo-container-item">
                      <el-select v-model="postForm.publish_name" :remote-method="getRemoteUserList" filterable default-first-option remote placeholder="Search publisher">
                        <el-option v-for="(item,index) in userListOptions" :key="item+index" :label="item" :value="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>
  
                  <!-- 发布时间 -->
                  <el-col :span="12">
                    <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">
                      <el-date-picker v-model="time" type="datetime" format="yyyy-MM-dd HH:mm:ss" style="width: 205px;" placeholder="Select date and time" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <!-- 重要程度 -->
                  <el-col :span="12">
                    <el-form-item label-width="90px" label="重要级别:" class="postInfo-container-item">
                      <el-select v-model="postForm.importance"  filterable default-first-option remote placeholder="Search importance">
                        <el-option v-for="(item,index) in importanceListOptions" :key="item+index" :label="item" :value="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label-width="120px" label="面向对象:" class="postInfo-container-item">
                      <el-select v-model="postForm.grade"  filterable default-first-option remote placeholder="Search grade">
                        <el-option v-for="(item,index) in gradeListOptions" :key="item+index" :label="item" :value="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <!-- 类型 -->
                  <!-- <el-col :span="12">
                    <el-form-item label-width="120px" label="任务类型:" class="postInfo-container-item">
                      <el-select v-model="postForm.type"  filterable default-first-option remote placeholder="Search type">
                        <el-option v-for="(item,index) in typeListOptions" :key="item+index" :label="item" :value="item" />
                      </el-select>
                    </el-form-item>
                  </el-col> -->
                </el-row>
                
                <el-row>
                  <!-- 任务地点 -->
                  <el-col :span="12">
                    <el-form-item label-width="90px" label="任务地点:" class="postInfo-container-item">
                      <el-select v-model="postForm.task_location" filterable default-first-option remote placeholder="Search place">
                        <el-option v-for="(item,index) in placeListOptions" :key="item+index" :label="item" :value="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <!--积分-->
                  <el-col :span="12">
                    <el-form-item label-width="120px" label="任务积分:" class="postInfo-container-item">
                      <el-select v-model="postForm.points"  filterable default-first-option remote placeholder="Search point">
                        <el-option v-for="(item,index) in pointListOptions" :key="item+index" :label="item" :value="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row>
                  <!-- 开始/结束时间 -->
                  <el-col :span="12">
                  <el-form-item label-width="90px" label="开始时间:" class="postInfo-container-item">
                    <el-date-picker v-model="start_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" style="width: 205px;" placeholder="Select date and time" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="120px" label="结束时间:" class="postInfo-container-item">
                    <el-date-picker v-model="end_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" style="width: 205px;" placeholder="Select date and time" />
                  </el-form-item>
                </el-col>
              </el-row>
                
                <el-row>
                  <el-col :span="12">
                  <!-- 摘要 -->
                    <el-form-item style="margin-bottom: 40px;" label-width="90px" label="任务内容 :" >
                      <el-input v-model="postForm.task_content" :rows="1" type="textarea" class="task-textarea" autosize placeholder="Please enter the content" />
                      <span v-show="contentLength" class="word-counter">{{ contentLength }}words</span>
                    </el-form-item> 
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
          <!-- 上传图片 -->
          <el-form-item label-width="90px" label="任务图片:" prop="image" style="margin-bottom: 30px;" class="postInfo-container-item">
            <Upload v-model="postForm.image" />
          </el-form-item>
        </div>
      </el-form>
    </div>
  </template>
  
  <script>
  import Upload from '@/components/Upload/SingleImage'
  import MDinput from '@/components/MDinput'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import { validURL } from '@/utils/validate'
  import { fetchTaskById } from '@/api/task'
  import { searchUser } from '@/api/remote-search'
  
  const defaultForm = {
    status: 'draft',
    name: '', // 题目
    task_content: '', // 摘要
    image: '', // 图片
    time: undefined, // 展示时间
    start_time: undefined,
    end_time: undefined,
    id: undefined,
    importance: undefined,
    points:'',
    grade:''
  }
  
  export default {
    name: 'TaskDetail',
    components: {  MDinput, Upload, Sticky },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.field + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.field + '为必传项'))
        } else {
          callback()
        }
      }
      return {
        postForm: Object.assign({}, defaultForm),
        loading: false,
        importanceListOptions:['主线任务','支线任务'],
        userListOptions: [],
        // typeListOptions: ['College','Academy','Class','Association'],
        placeListOptions: ['主教学楼','1号寝室','计算机学院','语言文学学院','机械学院','二食堂','操场','网球场'],
        pointListOptions:[1,2,3,4,5],
        gradeListOptions:[18,19,20,21,22,23,24],
        rules: {
          image: [{ validator: validateRequire }],
          name: [{ validator: validateRequire }],
          task_content: [{ validator: validateRequire }],
        },
        tempRoute: {}
      }
    },
    computed: {
      contentLength() {
        return this.postForm.task_content.length
      },
      time: {
        get() {
          return (+new Date(this.postForm.time))
        },
        set(val) {
          this.postForm.time = new Date(val)
        }
      },
      start_time: {
        get() {
          return (+new Date(this.postForm.start_time))
        },
        set(val) {
          this.postForm.start_time = new Date(val)
        }
      },
      end_time: {
        get() {
          return (+new Date(this.postForm.end_time))
        },
        set(val) {
          this.postForm.end_time = new Date(val)
        }
      }
    },
    created() {
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.fetchTaskData(id)
      }
      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      fetchTaskData(id) {
        fetchTaskById(id).then(response => {
          this.postForm = response.data
          this.postForm.title += `   Task Id:${this.postForm.id}`
          this.postForm.task_content += `   Task Id:${this.postForm.id}`
  
          this.setTagsViewTitle()
          this.setPageTitle()
        }).catch(err => {
          console.log(err)
        })
      },
      setTagsViewTitle() {
        const title = 'Edit Task'
        const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
        this.$store.dispatch('tagsView/updateVisitedView', route)
      },
      setPageTitle() {
        const title = 'Edit Task'
        document.title = `${title} - ${this.postForm.id}`
      },
      submitForm() {
        console.log(this.postForm)
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$notify({
              title: '成功',
              message: '发布任务成功',
              type: 'success',
              duration: 2000
            })
            this.postForm.status = 'published'
            this.loading = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      draftForm() {
        if (this.postForm.title.length === 0) {
          this.$message({
            message: '请填写必要的标题',
            type: 'warning'
          })
          return
        }
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
          duration: 1000
        })
        this.postForm.status = 'draft'
      },
      getRemoteUserList(query) {
        searchUser(query).then(response => {
          if (!response.data.items) return
          this.userListOptions = response.data.items.map(v => v.name)
        })
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  @import "@/styles/mixin";
  
  .createPost-container {
    position: relative;
  
    .createPost-main-container {
      padding: 40px 45px 20px 50px;
  
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;
  
        .postInfo-container-item {
          float: left;
        }
      }
    }
  
    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }
  
  .task-textarea ::v-deep {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }
  </style>